import { createAnimate } from './animate.js'
let itemHeight = 30;
let totalMS = 1500;
// 交互
let titles = document.querySelectorAll(".menu h2"); // 获取所有的h2标签
// 循环注册时间
for (let i = 0; i < titles.length; i++) {
    titles[i].onclick = function () {
        // 收起其他所有的菜单
        let beforeOpened = document.querySelector('.subMenu-container[status=opened');
        if (beforeOpened) {
            closeSubmenu(beforeOpened);
        }
        toggleSubmenu(this.nextElementSibling)
    }
}

// 打开子菜单
function openSubmenu(subMenu) {
    // 子菜单是有状态的(关闭、打开、播放动画)
    // 通过自定义属性，判定状态
    let status = subMenu.getAttribute("status");
    if (status && status !== 'closed') return;
    subMenu.setAttribute('status', 'playing')
    let to = itemHeight * subMenu.children.length;
    createAnimate({
        from: 0,
        to,
        totalMS,
        onMove: function (n) {
            subMenu.style.height = n + 'px';
        },
        onEnd() {
            subMenu.setAttribute('status', 'opened')
        }
    })
};

// 关闭子菜单
function closeSubmenu(subMenu) {
    // 子菜单是有状态的(关闭、打开、播放动画)
    // 通过自定义属性，判定状态
    let status = subMenu.getAttribute("status");
    if (status !== 'opened') return;
    subMenu.setAttribute('status', 'playing')
    let from = itemHeight * subMenu.children.length;
    createAnimate({
        from,
        to: 0,
        totalMS: 500,
        onMove: function (n) {
            subMenu.style.height = n + 'px';
        },
        onEnd() {
            subMenu.setAttribute('status', 'closed')
        }
    })
};

function toggleSubmenu(subMenu) {
    let status = subMenu.getAttribute('status');
    if (status === 'playing') {
        return;
    } else if (status === 'opened') {
        closeSubmenu(subMenu);
    } else {
        openSubmenu(subMenu);
    }
}